package util;


import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Class :  UploadUtil
 * Author: Qj
 * Date  : 2018/10/16 16:51
 **/
public class UploadUtil {


    public static File getChildDirectory(String  path, String fileName) {
        int hashCode=fileName.hashCode();
        //code的形式是1ef39b
        String code=Integer.toHexString(hashCode);
        //利用hashcode的十六进制的前两位，作为两级子目录的名字
        StringBuilder sb= new StringBuilder();
        sb.append(path);
        sb.append("/");
        sb.append(code.charAt(0)+"/");
        sb.append(code.charAt(1)+"/");
        File file=new File(sb.toString());
        //子目录如同：upload/a/c/     upload/1/a/
        if(!file.exists()) {
            file.mkdirs();
        }
        return file;
    }
    public static Map<String,String> renameFile(String uploadPath, String fileName){
        String name=null;
        Map<String,String> map = new HashMap<>();
        StringBuilder sb=new StringBuilder();
        sb.append(UUID.randomUUID().toString());
        sb.append("_");
        sb.append(fileName);
        File newFile = UploadUtil.getChildDirectory(uploadPath,sb.toString());
        String path=newFile.getAbsolutePath()+"/"+sb.toString();
        String[] pathAll=path.split("\\/");
        Pattern pattern=Pattern.compile("(?=upload\\/).*");
        Matcher matcher = pattern.matcher(path);
        if (matcher.find()){
            name= matcher.group();
        }
        map.put("path",path);
        map.put("name",name);
        return map;
    }


}
